package com.own.component.client.impl;

import com.own.component.client.base.RequestClientManager;
import com.own.component.client.property.ClientProperty;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * DefaultCookieRequestClientManager
 *
 * @author chenxueli
 * @date 2022-06-15 03:14:15
 */
public class DefaultCookieRequestClientManager extends RequestClientManager {

    public DefaultCookieRequestClientManager(ClientProperty clientProperty) {
        super(clientProperty);
    }

    /**
     * 获取客户端信息
     *
     * @return 客户端信息
     */
    @Override
    public String client(HttpServletRequest request) {
        if (request == null) {
            return null;
        }
        var token = request.getAttribute(this.getClientField());
        if (token != null) {
            return token.toString();
        }
        return getInCookie(request.getCookies());
    }

    /**
     * 从cookie中获取token信息
     *
     * @param cookies cookie列表信息
     * @return token信息
     */
    private String getInCookie(Cookie[] cookies) {
        for (var cookie : cookies) {
            if (cookie.getName().equals(this.getClientField())) {
                return cookie.getValue();
            }
        }
        return null;
    }

}
